package com.fs.ibox_h.dao.impl;

import com.fs.ibox_h.dao.UserDao;

import com.fs.ibox_h.pojo.User;

import com.fs.ibox_h.util.JDBCUtil;


import com.fs.ibox_h.vo.UserCondition;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import java.util.List;

public class UserDapImpl implements UserDao {


    @Override
    public List<User> selectByCnameState(int currentPageInt, int pageSizeInt, UserCondition userCondition) {
        StringBuffer  sql =new StringBuffer("SELECT * FROM tb_user where 1=1 ");
        List<Object> paramList = new ArrayList<>();
        appedSql(sql,paramList,userCondition);
        sql.append(" limit ? , ?");
        paramList.add((currentPageInt-1)*pageSizeInt);
        paramList.add(pageSizeInt);
        List<User> collections = JDBCUtil.executeQuery(sql.toString(), User.class, paramList.toArray());
        return collections;
    }

    @Override
    public int count(UserCondition userCondition) {
     //String 不可变字符串
        //StringBuffer(线程安全) StringBuilder(线程不安全)
        StringBuffer sql = new StringBuffer(" SELECT COUNT(1) FROM tb_user WHERE 1=1 ");
        //给?赋的值  值的顺序与?顺序一致
        List<Object> paramList = new ArrayList<>();
        //拼接sql
        appedSql(sql,paramList,userCondition);

        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            psmt = conn.prepareStatement(sql.toString());
            //给?赋值
            for (int i = 0; i < paramList.size(); i++) {
                psmt.setObject(i+1,paramList.get(i));
            }
            rs = psmt.executeQuery();
            rs.next();
            return rs.getInt(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(rs,psmt,conn);
        }
        return 0;
    }
    private void appedSql(StringBuffer sql, List<Object> paramList, UserCondition userCondition){
        if (userCondition!=null) {
            if (userCondition.getUsername() != null && !userCondition.getUsername().isEmpty()) {
                sql.append(" AND username like ? ");
                paramList.add("%" + userCondition.getUsername() + "%");
            }
            if (userCondition.getCstate() != null) {
//                    System.out.println(userCondition.getCstate());
                    sql.append(" AND state =?");
                    paramList.add(""+userCondition.getCstate());
            }
        }}
}
